package com.scj.vue3springboot.controller.captcha;

import com.google.code.kaptcha.Producer;
import com.scj.vue3springboot.constant.RedisConstant;
import com.scj.vue3springboot.exception.RRException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Class CaptchaController
 * @Author ShiChaojie
 * @Email:scj0725@qq.com
 * 生成验证码
 */
@Api(tags = "验证码")
@Controller
@Slf4j
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer producer;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    /**
     * 验证码
     */
    @GetMapping("captcha")
    @ApiOperation(value = "生成验证码")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        try (ServletOutputStream out = response.getOutputStream()) {
            // 生成文字验证码
            String code = producer.createText();
            // 获取图片验证码
            BufferedImage image = producer.createImage(code);
            // 存到Redis，2分钟失效
            redisTemplate.opsForValue().set(uuid, code, RedisConstant.REDIS_SAVE_DURATION_TWO, TimeUnit.MINUTES);

            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            // 处理可能的IO异常
            log.error("验证码生成失败");
            throw new RRException("验证码生成失败");
        }

    }
}
